package com.gmy.config;

import com.gmy.pojo.User;
import com.gmy.service.UserService;
import com.gmy.service.UserServiceImpl;
import lombok.val;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;

import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @version 1.0
 * @Description:
 * @Author 6
 * @Date 2021/8/25 10:09
 */

public class UserRealm extends AuthorizingRealm {


    @Autowired
    UserServiceImpl userServiceImpl;

    // 授权  二
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("执行了=>授权+doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 增加授权
        //info.addStringPermission("user:add");

        // 拿到当前用户的权限：
        Subject subject = SecurityUtils.getSubject();
        User currentUser =(User) subject.getPrincipal();
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    // 认证 一
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证+doGetAuthorizationInfo");

//        String username ="gmy123";
//        String password="123";
//        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//
//        // 用户名不一致
//        if(!token.getUsername().equals(username)){
//            return null;    // 抛出异常用户名不存在
//        }
//        //密码认证  shiro 做！！！
//        return new SimpleAuthenticationInfo("",password,"");

        // 连接真实的数据库-------：

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user =userServiceImpl.getUserByName(token.getUsername());
        if(user==null){
            return null;
        }
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");

    }
}
